<template>
  <div class="home">
    <van-nav-bar
      title="交通转运"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- <baidu-map class="map" center="大连" :zoom="zoom" @ready="handler">
      <bm-geolocation
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="true"
        @locationSuccess="getLoctionSuccess"
      ></bm-geolocation>
    </baidu-map> -->

    <!-- <baidu-map class="map" center="大连"></baidu-map> -->

    <!-- <van-nav-bar title="交通转运" left-text="" /> -->
    <div class="content" validate-first>
      <!-- taskNo:'111',//任务编码 -->

      <!-- task_type:'',//管控方式 -->
      <van-field
        input-align="right"
        label="管控方式"
        readonly
        v-model="item.taskType"
        name="pattern"
      />
      <!-- task_status:'',//任务状态 -->
      <van-field
        input-align="right"
        label="任务状态"
        readonly
        v-model="item.taskStatus"
        name="pattern"
      />
      <!-- startAddress:'',//始发地址 -->
      <van-field
        input-align="right"
        label="始发地址"
        readonly
        v-model="item.startAddress"
        name="pattern"
      />
      <!-- startAddressTel:'',//始发地联系电话 -->
      <van-field
        input-align="right"
        label="始发地联系电话"
        readonly
        v-model="item.startAddressTel"
        name="pattern"
      />
      <!-- startAddressContact:'',//始发地联系人 -->
      <van-field
        input-align="right"
        label="始发地联系人"
        readonly
        v-model="item.startAddressContact"
        name="pattern"
      />
      <!-- destinationContact:'',//目的地联系人 -->
      <van-field
        input-align="right"
        label="目的地联系人"
        readonly
        v-model="item.destinationContact"
        name="pattern"
      />
      <!-- destinationTel:'', //目的地电话 -->
      <van-field
        input-align="right"
        label="目的地电话"
        readonly
        v-model="item.destinationTel"
        name="pattern"
      />
      <!-- destinationAddress:'',//目的地地址 -->
      <van-field
        input-align="right"
        label="目的地地址"
        readonly
        v-model="item.destinationAddress"
        name="pattern"
      />
      <!-- controlStartDate:'',//管控开始日期 -->
      <van-field
        input-align="right"
        label="管控开始日期"
        readonly
        v-model="item.controlStartDate"
        name="pattern"
      />
      <!-- controlEndData:'',//管控解除日期 -->
      <van-field
        input-align="right"
        label="管控解除日期"
        readonly
        v-model="item.controlEndDate"
        name="pattern"
      />
      <!-- transportDriver:'',//转运司机 -->
      <van-field
        input-align="right"
        label="转运司机"
        readonly
        v-model="item.transportDriverName"
        name="pattern"
      />
      <!-- transportCar:'',//转运车辆 -->
      <van-field
        input-align="right"
        label="转运使用车辆"
        readonly
        v-model="item.transportCarName"
        name="pattern"
      />
      <div style="margin: 16px">
        <!-- <van-button round block type="primary" native-type="submit"> -->
        <van-button
          round
          block
          type="primary"
          @click="showStart()"
          v-if="item.taskStatus == '未开始'"
        >
          开始任务
        </van-button>
        <van-button
          round
          block
          type="danger"
          @click="showEnd()"
          v-if="item.taskStatus == '进行中'"
        >
          结束任务
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  startTask,
  endTask,
  findTaskData,
  addTaskLocationPoint
} from '@/api/traffic/traffic'
import { Toast, Dialog } from 'vant'
export default {
  data () {
    return {
      center: { lng: 121.617905, lat: 38.91001 },
      zoom: 12,

      list: [],
      page: 0, // 页数
      totalPage: null, // 全部条数
      loading: false,
      finished: false,
      showEndFlag: false,
      showStartFlag: true,

      // status:['未开始','进行中','已完成','已取消'],
      item: {
        id: '',
        taskNo: '', // 任务编码
        taskType: '', // 管控方式
        taskStatus: '', // 任务状态
        startAddress: '', // 始发地址
        startAddressTel: '', // 始发地联系电话
        startAddressContact: '', // 始发地联系人
        destinationContact: '', // 目的地联系人
        destinationTel: '', // 目的地电话
        destinationAddress: '', // 目的地地址
        controlStartDate: '', // 管控开始日期
        controlEndDate: '', // 管控解除日期
        transportDriver: '', // 转运司机
        transportCar: '' // 转运车辆
      }
    }
  },
  mounted () {
    this.init(this.$route.query.id)
    this.handler()
    // this.item = this.$route.query.row
    // this.item.controlStartData  = this.$route.query.row.controlStartData
  },
  created () {},
  methods: {
    getLoctionSuccess (point, AddressComponent, marker) {
      console.log('point=====', point)
      console.log('marker=====', marker)
      // if (navigator.geolocation) {
      //   //获取当前地理位置信息
      //   navigator.geolocation.getCurrentPosition(onSuccess, onError, options)
      // } else {
      //   alert('你的浏览器不支持HTML5来获取地理位置信息。')
      // }

      // map.clearOverlays()
      // let Icon_0 = new BMap.Icon(
      //   'icon/map_marker_check.png',
      //   new BMap.Size(64, 64),
      //   { anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36) }
      // )
      // var myMarker = new BMap.Marker(
      //   new BMap.Point(point.point.lng, point.point.lat),
      //   { icon: Icon_0 }
      // )
      // map.addOverlay(myMarker)
      this.center.lng = point.point.lng
      this.center.lat = point.point.lat
    },
    handler ({ BMap, map }) {
      // var point = new BMap.Point(116.331398, 39.897445)
      // map.centerAndZoom(point, 12)

      // var geolocation = new BMap.Geolocation()
      // // 开启SDK辅助定位
      // geolocation.enableSDKLocation()
      // geolocation.getCurrentPosition(function (r) {
      //   if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      //     var mk = new BMap.Marker(r.point)
      //     map.addOverlay(mk)
      //     map.panTo(r.point)
      //     alert('您的位置：' + r.point.lng + ',' + r.point.lat)
      //   } else {
      //     alert('failed' + this.getStatus())
      //   }
      // })

      var point = new BMap.Point(116.331398, 39.897445)
      map.centerAndZoom(point, 12)

      var geolocation = new BMap.Geolocation()
      // 开启SDK辅助定位
      geolocation.enableSDKLocation()
      geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          var mk = new BMap.Marker(r.point)
          map.addOverlay(mk)
          map.panTo(r.point)
          alert('您的位置：' + r.point.lng + ',' + r.point.lat)
        } else {
          alert('failed' + this.getStatus())
        }
      })

      // var point = new BMap.Point(116.331398, 39.897445)
      // map.centerAndZoom(point, 12)
      // var geolocation = new BMap.Geolocation()
      // geolocation.getCurrentPosition(
      //   function (r) {
      //     if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      //       var mk = new BMap.Marker(r.point)
      //       map.addOverlay(mk)
      //       map.panTo(r.point)
      //       alert('您的位置：' + r.point.lng + ',' + r.point.lat)
      //     } else {
      //       alert('failed' + this.getStatus())
      //     }
      //   },
      //   { enableHighAccuracy: true }
      // )

      // console.log(BMap, map)
      // this.$nextTick(function () {
      //   const geolocation = new BMap.Geolocation()
      //   console.log('geolocation=====', geolocation)
      //   geolocation.enableSDKLocation()
      //   geolocation.getCurrentPosition(function (r) {
      //     console.log(r, 'aaaa')
      //     console.log('this.getStatus()=====', this.getStatus())
      //     if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      //       const { lat = null, lng = null } = r.point
      //       var mk = new BMap.Marker(r.point)
      //       console.log('mk======', mk)
      //       let point = new BMap.Point(lng, lat)
      //       console.log('point======', point)
      //     }
      //   })
      // })
      // this.center.lng = point.lng
      // this.center.lat = point.lat
      // this.zoom = 12
      //   navigator.geolocation.getCurrentPosition(function (position) {
      //     //得到html5定位结果
      //     var x = position.coords.longitude
      //     var y = position.coords.latitude
      // console.log('x===',x,'====y===',y)
      //     //由于html5定位的结果是国际标准gps，所以from=1，to=5
      //     //下面的代码并非实际是这样，这里只是提供一个思路
      //     BMap.convgps(x, y, 1, 5, function (convRst) {
      //       var point = new BMap.Point(convRst.x, convRst.y)
      //       //这个部分和上面的代码是一样的
      //       var marker = new BMap.Marker(point)
      //       console.log('marker======',marker)
      //       map.addOverlay(marker)
      //       map.panTo(point)
      //     })
      //   })
    },

    startTime () {
      this.timer = window.setInterval(() => {
        setTimeout(() => {
          console.log('timer=========', this.timer)
          console.log('Time==========' + new Date())
          addTaskLocationPoint({
            taskId: this.$route.query.id,
            locationInfo: '116.397128,39.916527'
          }).then((res) => {
            if (res.data.errcode === 0) {
            }
          })
        }, 0)
      }, 5000) // 30000
      localStorage.setItem('taskStarId', this.$route.query.id)
      localStorage.setItem('taskStatus', this.timer)
    },
    downTime () {
      console.log('downtime=====', localStorage.getItem('taskStatus'))
      window.clearInterval(localStorage.getItem('taskStatus'))
      localStorage.removeItem('taskStatus')
      localStorage.removeItem('taskStarId')
      console.log('localstorage======' + localStorage.getItem('taskStatus'))
    },
    init (id) {
      findTaskData(id).then((res) => {
        if (res.data.errcode === 0) {
          this.item = res.data.data
          this.item.taskType = this.getTaskTypeName(res.data.data.taskType) // 管控方式
          this.item.taskStatus = this.getTaskStatusName(
            res.data.data.taskStatus
          ) // 任务状态
          this.item.controlStartDate = this.unixTimeToDate(
            res.data.data.controlStartDate
          )
          this.item.controlEndDate = this.unixTimeToDate(
            res.data.data.controlEndDate
          )
        }
      })
    },
    unixTimeToDate (value) {
      if (!value) {

      } else {
        let date = new Date(value)
        let y = date.getFullYear()
        let MM = date.getMonth() + 1
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate()
        d = d < 10 ? '0' + d : d
        let h = date.getHours()
        h = h < 10 ? '0' + h : h
        let m = date.getMinutes()
        m = m < 10 ? '0' + m : m
        let s = date.getSeconds()
        s = s < 10 ? '0' + s : s
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
      }
    },
    getTaskTypeName (taskType) {
      if (taskType == '0') {
        return '居家隔离'
      } else if (taskType == '1') {
        return '集中隔离'
      } else if (taskType == '2') {
        return '医院治疗'
      }
    },
    getTaskStatusName (taskStatus) {
      if (taskStatus == '0') {
        return '未开始'
      } else if (taskStatus == '1') {
        return '进行中'
      } else if (taskStatus == '2') {
        return '已完成'
      } else if (taskStatus == '3') {
        return '已取消'
      }
    },
    showStart () {
      if (localStorage.getItem('taskStatus') != null) {
        Dialog.alert({
          message: '您有任务正在进行中',
          showCancelButton: false,
          showConfirmButton: false
        }).then(() => {})
        const TIMEOUT = setTimeout(() => {
          Dialog.close()
          clearTimeout(TIMEOUT)
        }, 2000)
        return
      }

      startTask({ id: this.item.id }).then((res) => {
        if (res.data.errcode === 0) {
          this.showStartFlag = false
          this.showEndFlag = true
          this.init(this.item.id)
          this.startTime()
          Dialog.alert({
            message: '提交成功',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
        } else {
          Dialog.alert({
            message: '任务不能进行',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
        }
      })
    },
    showEnd () {
      endTask({ id: this.item.id, transportDriver: this.item.transportDriver, transportCar: this.item.transportCar }).then((res) => {
        if (res.data.errcode === 0) {
          this.showStartFlag = false
          this.showEndFlag = true
          this.init(this.$route.query.id)
          this.downTime()
          Dialog.alert({
            message: '提交成功',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
        } else {
          Dialog.alert({
            message: '任务不能取消',
            showCancelButton: false,
            showConfirmButton: false
          }).then(() => {})
          const TIMEOUT = setTimeout(() => {
            Dialog.close()
            clearTimeout(TIMEOUT)
          }, 2000)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.map {
  width: 100%;
  height: 400px;
}
.home {
  img {
    width: 100%;
  }
  .dialog-container {
    height: 70px;
    overflow-y: auto;
  }
  .get-area {
    width: 100%;
    padding: 0 0.8rem;
    font-size: 0.747rem;
    color: #fff;
    background-color: #1989fa;
    border: 0.053rem solid #1989fa;
    height: 2.347rem;
    line-height: 2.347rem;
    text-align: center;
    border-radius: 0.107rem;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 10px;
  }
  /deep/.van-field__label {
    width: 8em;
  }
  /deep/.van-field__error-message {
    text-align: right;
  }
  .title {
    // font-size: 28px;
    text-indent: 20px;
    padding: 50px 0 20px;
  }
  .container {
    width: 90%;
    height: 80vh;
    overflow-y: auto;
    border: 1px solid #adadad;
    margin: auto;
    .item {
      margin: 10px;
    }
  }
}
.up-and-down {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f1f3f4;
  height: 80px;
  color: #333;
}
.content {
  // border-bottom: 10px solid #ccc;
}
</style>
